package com.hmall.item.web;

import com.hmall.feign.pojo.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@Slf4j
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    /**
     * 分页查询
     */
    @GetMapping("/list")
    public PageDTO<Item> list(Integer page, Integer size) {
        PageDTO<Item> pageDTO = itemService.pagingQuery(page, size);
        return pageDTO;
    }

    /**
     * 根据id查询数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item getItem(@PathVariable Long id) {
        Item item = itemService.CommodityInquiry(id);
        return item;
    }

    /**
     * 新增商品
     */
    @PostMapping
    public void postItem(@RequestBody Item item) {
        itemService.AddingItems(item);
    }

    /**
     * 商品上下架
     */
    @PutMapping("/status/{id}/{status}")
    public void putStatus(@PathVariable() Long id, @PathVariable Integer status) {
        itemService.ChangingState(id, status);
    }

    /**
     * 修改商品
     */
    @PutMapping
    public void putItem(@RequestBody Item item) {
        itemService.amendItem(item);
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public void deleteItem(@PathVariable Long id) {
        itemService.deleteQuery(id);
    }


    /**
     * 根据商品id扣减库存
     *
     * @param itemId 商品id
     * @param num    扣减商品数量
     */
    @GetMapping("/stock/{itemId}/{num}")
    public boolean deductStock(@PathVariable("itemId") Long itemId, @PathVariable("num") Integer num) {
        log.info("开始扣减库存，商品id:{},扣减数量：{} ", itemId, num);
        // 入参检查
        if (Objects.isNull(itemId)) {
            throw new RuntimeException("商品为空");
        }
        Item item = itemService.getById(itemId);
        // 存在性校验
        if (Objects.isNull(item)) {
            throw new RuntimeException("商品不存在");
        }
        // 库存判断
        if (item.getStock() + num < 0) {
            return false;
        }
        item.setStock(item.getStock() + num);
        boolean result = itemService.updateById(item);
        log.info("商品库存扣减结果：{}", result);
        return result;
    }
}
